<?php
global $_W, $_GPC;
$book = get('select id from ' .tb('book'). " where id = '{$_GPC['id']}'");
if(empty($book)) MSG('课程不存在', referer(), 'error');
$weid = $_W['uniacid'];
set_time_limit(0);
include_once '../addons/junsion_listenbook/excel/oleread.php';
include_once '../addons/junsion_listenbook/excel/excel.php';
$error = $_FILES [ "txtfile" ][ "error" ];
if ( !empty( $_FILES ['txtfile']['name'] ) && $error  ==  UPLOAD_ERR_OK ) {
	$tmp_name  =  $_FILES [ "txtfile" ][ "tmp_name" ];
	$name = $_FILES [ "txtfile" ][ "name" ];
	$filename  =  ATTACHMENT_ROOT.date ( 'Ymdhis' ).'.'.pathinfo($name,PATHINFO_EXTENSION);
	if (move_uploaded_file ( $tmp_name , $filename )) {
		// error_reporting(E_ALL ^ E_NOTICE);
		$xls = new Spreadsheet_Excel_Reader ();
		$xls->setOutputEncoding ( 'utf-8' ); // 设置编码
		$xls->read ( $filename ); // 解析文件
		for($i = 2; $i <= $xls->sheets [0] ['numRows']; $i ++) {
			$data_values [] = $xls->sheets [0] ['cells'] [$i];
		}
	}
	$inert_sql = "INSERT INTO ".tablename($this->modulename.'_book_chapter')." (`uniacid`,`bid`,`did`,`title`,`link`,`sort`,`type`,`detail`) ";
	$insert_val = "";
	foreach($data_values as $value){
		if(empty($value[1]) && empty($value[2]))break;
		if($value[1] != '' && $value[2] != '' && $value[3] == ''){
			$dict = get('select id from ' . tb('book_directory') . " where title = '{$value[1]}' and bid = '{$_GPC['id']}' and uniacid = '{$_W['uniacid']}' limit 1");
			if(empty($dict)){
				$dict_data = array(
						'uniacid' => $_W['uniacid'],
						'bid' => $_GPC['id'],
						'title' => $value[1],
						'sort' => $value[2],
				);
				insert('book_directory',$dict_data);
				$dict_id = pdo_insertid();
			}else{
				$dict_id = $dict['id'];
			}
			continue;
		}
		if(!empty($insert_val)){
			$insert_val .= ", ";
		}
		$detail = htmlspecialchars_decode($value[6]);
		$insert_val .= " ( '{$weid}','{$_GPC['id']}','{$dict_id}','{$value[2]}','{$value[3]}','{$value[4]}','{$value[5]}','{$detail}' ) ";
		$count++;
	}
	if(!empty($insert_val)){
		$inert_sql .= " VALUES ".$insert_val;
		$ret = pdo_query($inert_sql);
	}
	if($ret > 0){
		message('导入记录 '.$count.' 条',referer());
	}else{
		message('导入错误，请刷新重试！');
	}
}else{
	message('抱歉！导入信息有误，请重试',referer(),'error');
}